﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Net;
using System.Web.Script.Serialization;
using System.IO;

namespace HereIamService
{
	public partial class MyNewService : ServiceBase
	{
		#region Just to hold response JSON data

		private class LatLong
		{
			public string latitude;
			public string longitude;
			public string accuracy;
		}

		private class Geolocation
		{
			public LatLong location;
			public string access_token;
		}

		#endregion

		//private localhost.MyWebService myWebService;
		//private vn.unitech.mobile
		private System.Timers.Timer myTimer = new System.Timers.Timer();
		private JavaScriptSerializer serializer = new JavaScriptSerializer();
		// Dùng gear dll
		//private GearsTypelib.ModuleWrapperClass gears = new GearsTypelib.ModuleWrapperClass();

		public MyNewService()
		{
			InitializeComponent();

			// Đăng kí event log
			if ( !System.Diagnostics.EventLog.SourceExists( "DoDyLogSourse" ) )
			{
				System.Diagnostics.EventLog.CreateEventSource( "DoDyLogSourse", "DoDyLog" );
			}

			// the event log source by which 
			// the application is registered on the computer
			eventLog1.Source = "DoDyLogSourse";
			eventLog1.Log = "DoDyLog";
		}

		protected override void OnStart( string[] args )
		{
			eventLog1.WriteEntry( "my service started" );

			// Khởi tạo web service
			//myWebService = new HereIamService.localhost.MyWebService();

			#region Khởi tạo timer
			//myTimer = new System.Timers.Timer();
			myTimer.Elapsed += new System.Timers.ElapsedEventHandler( myTimer_Elapsed );
#if (DEBUG)
			{
				// set khoảng nghỉ của timer là 10 giây
				myTimer.Interval = 10*1000;
			}
#else
			{
				// set khoảng nghỉ của timer là 1 giờ
				timer1.Interval = 3600*1000;
			}
#endif
			#endregion

			myTimer.Start();
			eventLog1.WriteEntry( "timer started" );
		}

		void myTimer_Elapsed( object sender, System.Timers.ElapsedEventArgs e )
		{

			//// Gọi web service method
			//string hello = myWebService.HelloWorld();
			//eventLog1.WriteEntry( hello );



			// Dùng mshtml.dll
			//mshtml.IHTMLDocument doc = ( mshtml.IHTMLDocument )axwebBrowser.Document;
			//mshtml.IHTMLWindow parentWin = doc.parentWindow;
			//parentWin.execScript( "test(100)", "javascript" );

			// Dùng tool của Windows
			//System.Diagnostics.Process.Start( @"C:\windows\system32\wscript.exe", @"D:\Development tools\HereIamService\HereIamService\bin\Debug\hellogeo.js" );

			// Web browser cho winform
			//webBrowser1 = new System.Windows.Forms.WebBrowser();


			#region Use WebClient for http command POST (contentType = "application/json")
			// Create a new WebClient instance
			WebClient myWebClient = new WebClient();
			myWebClient.Headers.Add( "Content-Type", "application/json" );

			// Display the headers in the request
			//eventLog1.WriteEntry( "Resulting Request Headers: " );
			//eventLog1.WriteEntry( myWebClient.Headers.ToString() );

			// Apply ASCII/UTF8 Encoding to obtain the string as a byte array

			string postData = "{ \"version\": \"1.1.0\", \"host\": \"maps.google.com\" }";
			byte[] byteArray = Encoding.UTF8.GetBytes( postData );
			// Upload the input string using the HTTP 1.0 POST method
			byte[] responseArray = myWebClient.UploadData( "http://www.google.com/loc/json", "POST", byteArray );

			string geoResponse = Encoding.UTF8.GetString( responseArray );

			// Decode and display the response
			eventLog1.WriteEntry( "Response received was " + geoResponse );

			Geolocation loc = new Geolocation();
			// Deserialize
			try
			{
				loc = serializer.Deserialize<Geolocation>( geoResponse );
			}
			catch ( Exception ex )
			{
				eventLog1.WriteEntry( ex.Message );
			}
			finally
			{
				eventLog1.WriteEntry( loc.location.latitude + " " + loc.location.longitude );
			}
#endregion

/*
			string response = "err!";
			try
			{
			WebClient myWebClient = new WebClient();
			myWebClient.Headers.Add( "Content-Type", "text/xml;charset=\"utf-8\"" );
            string postData = "";
            byte[] byteArray = Encoding.UTF8.GetBytes( postData );
            // Upload the input string using the HTTP 1.0 POST method
            byte[] responseArray = myWebClient.UploadData( "http://mobile.unitech.vn:7000/Locatorservice/service.asmx/UpdateLocator?id=COMPU1&currentLat=16&currentLng=102&flg=1", "POST", byteArray );

            response = Encoding.UTF8.GetString( responseArray );
			}
			catch (Exception ex)
			{
				eventLog1.WriteEntry( ex.Message );
			}
			eventLog1.WriteEntry( response );
*/

/* Code example when using ContentType = "application/x-www-form-urlencoded"

						ASCIIEncoding encoding = new ASCIIEncoding();

						postData += "?userID=" + xxx;
						postData += "&password=" + xxxxxxx; postData += "&data=" + xmldoc.InnerXml;

						data = encoding.GetBytes(postData); //url-encoded

						// Prepare web request...
						HttpWebResponse WResponse = null;HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://www.abc.com/data/Default.aspx");myRequest.Method = "POST";myRequest.ContentType = "application/x-www-form-urlencoded";

						myRequest.ContentLength = data.Length;

						Stream newStream = myRequest.GetRequestStream();

						// Send the data.

						newStream.Write(data, 0, data.Length);

						newStream.Close(); //close the stream

						//Get web Response

						WResponse = (HttpWebResponse)myRequest.GetResponse();
*/


#region Http request through SOAP

			string soap = 
@"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" 
   xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" 
   xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
  <soap:Body>
    <UpdateLocator xmlns=""http://tempuri.org/"">
      <id>COMP1</id>
      <currentLat>" + loc.location.latitude + @"</currentLat>
      <currentLng>" + loc.location.longitude + @"</currentLng>
      <flg>1</flg>
    </UpdateLocator>
  </soap:Body>
</soap:Envelope>";

			string responseStr = "not set";

			try
			{
				HttpWebRequest req = ( HttpWebRequest )WebRequest.Create( "http://mobile.unitech.vn:7000/Locatorservice/service.asmx" );
				req.Headers.Add( "SOAPAction", "\"http://tempuri.org/UpdateLocator\"" );
				req.ContentType = "text/xml;charset=\"utf-8\"";
				req.Accept = "text/xml";
				req.Method = "POST";

				using ( Stream stm = req.GetRequestStream() )
				{
					using ( StreamWriter stmw = new StreamWriter( stm ) )
					{
						stmw.Write( soap );
					}
				}

				WebResponse response = req.GetResponse();
				using ( Stream responseStream = response.GetResponseStream() )
				using ( StreamReader srd = new StreamReader( responseStream ) )
				{
					responseStr = srd.ReadToEnd();
				}
				eventLog1.WriteEntry( responseStr );
			}
			catch ( Exception ex )
			{
				eventLog1.WriteEntry( ex.Message );
			}
#endregion

		}

		protected override void OnStop()
		{
			myTimer.Stop();
			myTimer.Dispose();
			eventLog1.WriteEntry( "timer stopped" );
			eventLog1.WriteEntry( "my service stopped" );
		}

		protected override void OnContinue()
		{
			eventLog1.WriteEntry( "my service is continuing in working" );
		}
	}
}
